package com.wobangkj.common.api.file;

import com.wobangkj.common.model.file.FileUri;
import com.wobangkj.common.util.file.DownloadUtil;
import com.wobangkj.common.util.file.ImageUtil;
import com.wobangkj.tool.api.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 文件上传
 *
 * @author lu
 */

@Controller
@RequestMapping(value = "/file")
@Slf4j
public class FileController {

	// 文件上传路径
	private static final String UploadPath = "common-service/static/file/";

	@PostMapping("/upload")
	@ResponseBody
	public Object upload(@RequestParam("file") MultipartFile file, String name, Integer width, Integer height) {

		if (file.isEmpty()) {
			return Result.GetMapData(Result.CodeFile, "文件不能为空");
		}

		String filename;
		Path   path;
		try {
			// 文件字节数据
			byte[] bytes = file.getBytes();
			filename = file.getOriginalFilename();
			// jar 包路径问题
			//获取根目录
			File rootFile = new File("");
			File upload   = new File(rootFile.getAbsolutePath(), UploadPath);
			if (!upload.exists()) upload.mkdirs();

			String rootPath = upload.getAbsolutePath();// + "/" + UploadPath;

			// 获取文件的后缀名
			String suffixName = filename.substring(filename.lastIndexOf("."));

			if (name != null && !name.equals("")) {
				filename = name + suffixName;
			} else {
				filename = UUID.randomUUID().toString().replace("-", "") + suffixName;
			}

			path = Paths.get(rootPath + "/" + filename);

			Files.write(path, bytes);
			log.info("文件根目录==>rootFile: " + rootFile.getAbsolutePath());
			log.info("文件目录==>rootPath: " + rootPath);
			log.info("文件路径==>: " + path.toString());

			// 图片常用类型压缩
			// 异步操作
			new Thread(() -> {
				String[] imgType = new String[]{"png", "jpg", "jpeg"};
				for (String imgTp : imgType) {
					log.info("文件类型:" + suffixName);
					if (suffixName.equalsIgnoreCase("." + imgTp)) {
						BufferedImage bufferedImage = ImageUtil.compressImage(path.toString(), width, height, false);
						// 写回文件
						try {
							ImageIO.write(bufferedImage, imgTp, Files.newOutputStream(path));
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}).start();

		} catch (IOException e) {
			e.printStackTrace();
			return Result.GetMapData(Result.CodeFile, "文件上传错误", e.toString());
		} catch (Exception e) {
			return Result.GetMapData(Result.CodeError, e.toString());
		}
		Map<String, Object> map = new HashMap<>();
		map.put("path", UploadPath + filename);

		return Result.GetMapData(Result.CodeFile, Result.MsgFile, map);
	}

	@PostMapping("/uri")
	@ResponseBody
	public Object uri(@RequestBody FileUri data) {

		//String filename;
		if (data.getName() == null) {
			data.setName(UUID.randomUUID().toString().replace("-", ""));
		}
		//获取根目录
		File rootFile = new File("");
		File upload   = new File(rootFile.getAbsolutePath(), UploadPath);
		if (!upload.exists()) upload.mkdirs();

		// 获取文件的后缀名
		//String suffixName = uri.substring(uri.lastIndexOf("."));

		DownloadUtil.downloadHttpUrl(data.getUri(), upload.getAbsolutePath() + "/", data.getName() + "." + data.getType());
		Map<String, Object> map = new HashMap<>();
		map.put("path", UploadPath + data.getName() + "." + data.getType());
		return Result.GetMapData(Result.CodeFile, Result.MsgFile, map);
	}
}
